package org.lgiavedoni.android.franq.core.position;

import java.util.List;

import lombok.Data;
import lombok.EqualsAndHashCode;

import org.lgiavedoni.android.franq.core.bean.WifiNetwork;
import org.lgiavedoni.android.franq.core.sync.DaoSynObject;
import org.lgiavedoni.android.franq.util.googe.MapsUtil;

import android.location.Location;
import android.telephony.gsm.GsmCellLocation;

@Data
@EqualsAndHashCode(callSuper=true)
public class Position extends DaoSynObject {

	private double latitude = 0;
	private double longitude = 0;
	private List<WifiNetwork> networks;
	private GsmCellLocation cellLocation;

	private Position() { 
		super();
	}

	public Position(List<WifiNetwork> networks) {
		super();
		this.networks = networks;
	}

	public Position(double latitude, double longitude) {
		super();
		this.latitude = latitude;
		this.longitude = longitude;
	}

	public static Position createInstanceFrom(Location location) {
		if (location == null)
			return getDefault();
		Position p = new Position();
		p.setLatitude(location.getLatitude());
		p.setLongitude(location.getLongitude());

		return p;
	}
	
	public static Position createInstanceFrom(GsmCellLocation location) {
		if (location == null)
			return getDefault();
		Position p = new Position();
		p.setCellLocation(location);
		return p;
	}

	public static Position getDefault() {
		Position p = new Position();
		// p.setLatitude(RandomUtil.valueBetween(-90, 90));
		// p.setLongitude(RandomUtil.valueBetween(-180, 180));
		p.setLatitude(50);
		p.setLongitude(90);
		return p;
	}

	public String getMapURL() {
		return MapsUtil.getURL(this);
	}

	public int getPrecision() {
		String p = new Double(latitude).toString();
		return (p.length() - p.indexOf(".") - 1);
	}

	public boolean isUnknow() {
		return isUnknowLocation() && isUnknowNetworks() && isUnknowCell()? true : false;
	}

	public boolean isUnknowLocation() {
		return (latitude == 0 && longitude == 0) ? true : false;
	}

	public boolean isUnknowNetworks() {
		return (networks == null || networks.size() == 0) ? true : false;
	}
	
	public boolean isUnknowCell() {
		return (cellLocation == null || cellLocation.getCid()==-1) ? true : false;
	}
	
	public void setCellLocation(GsmCellLocation location){
		this.cellLocation = location;
	}
	

	@Override
	public String toString() {
		StringBuffer s = new StringBuffer();
		s.append("Position ");
		if (latitude != 0 && longitude != 0) 
			s.append("[latitude=" + latitude + ", longitude=" + longitude + "] ");
		if (networks != null && networks.size() > 0) 
			s.append(" [Networks =" + networks.size() + "] ");
		
		if (cellLocation!=null) 
			s.append(" [CellLocation cid= " + cellLocation.getCid() + ", lac="+cellLocation.getLac()+"] ");
		return s.toString();
	}

}
